package org.example.hbase;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;

import java.io.IOException;

/**
 * @author zhl
 * @version 1.0
 * @ClassName
 * @date 2020/11/6 15:50
 */
public class HbaseConn {
    private static final HbaseConn INSTANCE = new HbaseConn();
    private static Configuration configuration; //hbase配置
    private static Connection connection; //hbase connection

    private HbaseConn() {
        try {
            if (configuration == null) {
                configuration = HBaseConfiguration.create();
                configuration.set("hbase.zookeeper.quorum", "mnode1:2181");
//                configuration.set("hbase.rootdir","hdfs://mnode1:9000/hbase");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取内部连接
     * @return
     */
    private Connection getConnection() {
        if (connection == null || connection.isClosed()) {
            try {
                connection = ConnectionFactory.createConnection(configuration);
                Admin admin = connection.getAdmin();
                HTableDescriptor[] tableDescriptor =admin.listTables();
                for (HTableDescriptor hTableDescriptor : tableDescriptor) {
                    System.out.println(hTableDescriptor.getNameAsString());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return connection;
    }

    /**
     * 获取HBase连接
     * @return
     */
    public static Connection getHBaseConn() {
        return INSTANCE.getConnection();
    }

    /**
     * 根据获取HBase的table对象
     * @param tableName
     * @return
     * @throws IOException
     */
    public static Table getTable(String tableName) throws IOException {
        return INSTANCE.getConnection().getTable(TableName.valueOf(tableName));
    }

    /**
     * 关闭连接
     */
    public static void closeConn() {
        if (connection != null) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        HbaseConn.getHBaseConn();
    }
}
